package com.ccx.coachsite.ui.softmgr;


import java.io.IOException;
import java.lang.ref.SoftReference;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.ccx.coachsite.R;
import com.ccx.coachsite.api.CoachSiteSoftMgrApiAccessor;
import com.ccx.coachsite.data.SystemConst;
import com.ccx.coachsite.downloadmgr.AsyncImageLoader;
import com.ccx.coachsite.downloadmgr.AsyncImageLoader.ImageCallback;
import com.ccx.coachsite.downloadmgr.DownloadItem;
import com.ccx.coachsite.downloadmgr.DownloadService;
import com.ccx.coachsite.downloadmgr.DownloadTool;
import com.ccx.coachsite.model.PageInfo;
import com.ccx.coachsite.model.ServerResult;
import com.ccx.coachsite.model.SoftCategoryItem;
import com.ccx.coachsite.model.SoftShareMessage;
import com.ccx.coachsite.ui.CommonAppView;
import com.ccx.coachsite.util.CrashTool;
import com.ccx.coachsite.util.FileUtil;
import com.ccx.coachsite.util.OpenShareTool;
import com.ccx.coachsite.util.U;


public class SoftMgrSoftListView extends CommonAppView {

	//初始化参数 Begin
	private HashMap<String, Object> paraMap = new HashMap<String, Object>();
	//初始化参数 End
	
	/*---------------控件对象---------------------------*/
	private ListView lv_required_list;			//显示列表
	private LinearLayout ll_on_loading_first; 	//第一次 正在加载...
	private LinearLayout ll_no_data_first;		//第一次 未找到数据或者网络错误
	private LinearLayout ll_on_loading_bottom;	//正在加载...
	private LinearLayout ll_no_data_bottom;		//未找到数据或者网络错误(底部)
	private TextView tv_nodata_error;			//未找到数据和出错的显示View
	private Button btn_nodata_reflash;			//未找到数据时刷新按钮
	private TextView tv_nodata_main;			//未搜索到数据时提示
	
	private LinearLayout ll_tab_on_loading; 	//分类刷新时的加载进度
	
	private View soft_cata;						//分类View
	
	private TextView selCataLable; //当前选中的分类
	private View ll_top;			//顶部返回菜单
	private TextView login_top_title;
	private ImageButton btn_back;
	public CommonAppView parentView;
	
	/*---------------其他变量---------------------------*/
//	private long mDataCount=0;//服务器端总记录数
	private DownloadStatusReceiver mDownloadStatusReceiver;//下载状态变化监听器
	private List<SoftInfo> tempList;
	
	private LoginReceiver mLoginReceiver;//登录成功监听器
	
	/*----------------公共变量-----------------------------*/

	private String mCurrentURL;
	private boolean isLast = false;
	private PageInfo lastPageInfo;
	private int nextPage=1;
	private boolean mIsDownloading=false;//是否处在下载中
	private UninstallReceiver mUninstallReceiver;
	
	private ListViewAdapter mAdapter;
	private Bitmap defBmp;//默认图标
	
	private final int EVENT_COMMON=10000;//通用事件
	private final int EVENT_FIRST_LOADING=10001;//首次加载结束事件
	private final int EVENT_LIST_SCROLL_END=10002;//列表滚动到最底，且加载结束
	private final int EVENT_CONNECTION_FAILED=10003;//网络异常
	private final int EVENT_BOTTOM_CONNECTION_FAILED=10004;//底部加载网络异常
	private final int EVENT_CATEGORY_END=10005;//分类加载完成
	
	private int mListType = TYPE_APP_LIST;
	public static final String EXTRA_SHARE_TYPE = "share_type";

	public static final String EXTRA_LIST_TYPE = "list_type";
	public static final int TYPE_APP_LIST = 1;			//应用分类列表
	public static final int TYPE_CATEGORY_LIST = 2;		//应用专题列表
	public static final int TYPE_SEARCH_LIST = 3;		//应用搜索列表
	
	public ServerResult<SoftCategoryItem> softCategoryResultCache;
	
	private ServerResult<SoftCategoryItem> softCategoryResult;
	
	/**类型URL*/
	private String reqTypeBaseURL = CoachSiteSoftMgrApiAccessor.API_SOFTMGR_TYPE_LIST;
	
	/**列表URL*/
	private String reqListBaseURL = CoachSiteSoftMgrApiAccessor.API_SOFTMGR_LIST;
	
	private static final int WHITE = 0xffffffff;
	private static final int BLACK = 0xff000000;
	private static final int BLUE = 0xff0000ff; //升级 安装的字体颜色
	
	private boolean firstLoadTab = true;
	/**分类ID*/
	private int catagoryID = 0;
	/**专题ID*/
	private int iTopicId = 0;
	
	private String keyWord = "";
	
	private boolean searchNameType = false;//false 通过关键词查询   True通过名称查询
	
	private int shareType; 	//应用类型  1.教程 2应用 3游戏 4专题
	
	private Context mContext;
	
	
	//初始化参数 Begin	
	private Callback resultCallBack = null;
	
	public Callback getResultCallBack() {
		return resultCallBack;
	}

	public void setResultCallBack(Callback resultCallBack) {
		this.resultCallBack = resultCallBack;
	}



	/**
	 * 列表加载回调接口
	 */
	public interface Callback {
		/**
		 * 开始加载列表数据
		 */
		public void onStarting();

		/**
		 * 主题数据加载完成
		 * 
		 * @param page
		 */
		public void onFinished(PageInfo page);
	}
	
	private Handler mEventHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			//首次加载结束
			case EVENT_FIRST_LOADING:
				if (softCategoryResult!=null && !softCategoryResult.isbNetworkProblem() && firstLoadTab ) {
					firstLoadTab = false;
					//分类加载完成
					ll_on_loading_first.setVisibility(View.GONE);
					ll_no_data_first.setVisibility(View.GONE);
					ll_tab_on_loading.setVisibility(View.GONE);
					
					ArrayList<SoftCategoryItem> listSoftCategory = softCategoryResult.itemList;
					if ( softCategoryResult.isbNetworkProblem() ) {//网络连接失败提示
						tv_nodata_error.setText(R.string.common_no_connection);
						ll_no_data_first.setVisibility(View.VISIBLE);
						
						return ;
					}else if ( listSoftCategory==null || listSoftCategory.size()==0 ){//未找到数据 
						tv_nodata_error.setText("");
						ll_no_data_first.setVisibility(View.VISIBLE);
						
						return ;
					}else{
						setCateLable(listSoftCategory);
						ll_on_loading_first.setVisibility(View.GONE);
						ll_tab_on_loading.setVisibility(View.GONE);
						lv_required_list.setVisibility(View.GONE);
						
						soft_cata.setVisibility(View.VISIBLE);
					}
				}
				
				ll_on_loading_first.setVisibility(View.GONE);
				ll_tab_on_loading.setVisibility(View.GONE);
				lv_required_list.setVisibility(View.VISIBLE);
				if(tempList==null||tempList.size()==0) //未找到数据
					
					ll_no_data_first.setVisibility(View.VISIBLE);
				else{
					mAdapter.clearListItems();
					mAdapter.addListItems(tempList);
					mAdapter.notifyDataSetChanged();
					
					//lv_required_list.setSelection(0);//回到顶部
	                if (!lv_required_list.isStackFromBottom()) {
	                	lv_required_list.setStackFromBottom(true);
	                }
	                lv_required_list.setStackFromBottom(false);
				}
				
				//完成加载后，执行回调函数
				if( null != resultCallBack && lastPageInfo!=null ) {
					resultCallBack.onFinished( lastPageInfo );
				}
				
				mIsDownloading=false;
				break;
			//普通刷新
			case EVENT_COMMON:
				if(mAdapter!=null)
					mAdapter.notifyDataSetChanged();
				break;
			//列表滚动到底部的加载事件
			case EVENT_LIST_SCROLL_END:
				ll_on_loading_bottom.setVisibility(View.GONE);
				if(tempList!=null)
				{
					mAdapter.addListItems(tempList);
					mAdapter.notifyDataSetChanged();					
				}
				mIsDownloading=false;
				break;
			//底部加载时网络连接失败提示
			case EVENT_BOTTOM_CONNECTION_FAILED:
				ll_no_data_bottom.setVisibility(View.VISIBLE);
			break;
			//网络连接失败提示
			case EVENT_CONNECTION_FAILED:
//				tv_nodata_error.setText(R.string.common_no_connection);
				ll_on_loading_first.setVisibility(View.GONE);
				ll_tab_on_loading.setVisibility(View.GONE);
				ll_no_data_first.setVisibility(View.VISIBLE);
				tv_nodata_error.setText(R.string.common_no_connection);
				btn_nodata_reflash.setOnClickListener(new ReflashClickListener());
				break;
			case EVENT_CATEGORY_END:
				//分类加载完成
				ll_on_loading_first.setVisibility(View.GONE);
				ll_no_data_first.setVisibility(View.GONE);
				ll_tab_on_loading.setVisibility(View.GONE);
				
				ArrayList<SoftCategoryItem> listSoftCategory = softCategoryResult.itemList;
				if ( softCategoryResult.isbNetworkProblem() ) {//网络连接失败提示
					tv_nodata_error.setText(R.string.common_no_connection);
					ll_no_data_first.setVisibility(View.VISIBLE);
				}else if ( listSoftCategory==null || listSoftCategory.size()==0 ){//未找到数据 
					tv_nodata_error.setText("");
					ll_no_data_first.setVisibility(View.VISIBLE);
				}else{
					setCateLable(listSoftCategory);
					ll_on_loading_first.setVisibility(View.GONE);
					ll_tab_on_loading.setVisibility(View.GONE);
					lv_required_list.setVisibility(View.GONE);
					
					soft_cata.setVisibility(View.VISIBLE);
				}
				
				break;
			}
		}
		
	};
	
	
	public SoftMgrSoftListView(Context context, HashMap<String, Object> initParaMap) {
		super(context);
		
		mContext=context;
		
		addView(R.layout.soft_mgr_soft_list);
			
        initView();
        
        defBmp=BitmapFactory.decodeResource(getResources(), R.drawable.soft_mgr_defualt_icon);

        //注册下载状态变化监听
		IntentFilter dlStatusFilter=new IntentFilter();
		dlStatusFilter.addAction(DownloadService.DOWNLOAD_STATUS_CHANGE_RECEIVER);
		mDownloadStatusReceiver=new DownloadStatusReceiver();
		mContext.registerReceiver(mDownloadStatusReceiver, dlStatusFilter);
		
		IntentFilter loginFilter=new IntentFilter();
		loginFilter.addAction(OpenShareTool.LOGIN_SUCCESS_RECEIVER);
		mLoginReceiver=new LoginReceiver();
		mContext.registerReceiver(mLoginReceiver, loginFilter);
		
        //安装与卸载软件的监听
        mUninstallReceiver=new UninstallReceiver();
        IntentFilter infilter=new IntentFilter();
        infilter.addAction(Intent.ACTION_PACKAGE_ADDED);
        infilter.addAction(Intent.ACTION_PACKAGE_REMOVED);
        infilter.addDataScheme("package");
        mContext.registerReceiver(mUninstallReceiver, infilter);
        
        //参数设置
        paraMap = initParaMap;
        
        //1.教程 2应用 3游戏 4专题
		Integer shareTypeObj = (Integer)paraMap.get(EXTRA_SHARE_TYPE);
		if ( shareTypeObj==null ) {
			shareType = SoftShareMessage.TYPE_APP_SHARE_TYPE;
		}else{
			shareType = shareTypeObj.intValue();
		}
        
		Integer listType = (Integer)paraMap.get(EXTRA_LIST_TYPE);
		
		if ( listType==null ) {
			mListType = TYPE_APP_LIST;
		}else{
			mListType = listType.intValue();
		}
		
		//搜索结果不响应点击事件去，去掉点击背景色
		if ( mListType==TYPE_SEARCH_LIST ) {
			 //消除点击背景
			lv_required_list.setSelector(new ColorDrawable(Color.TRANSPARENT));
		}
		 
		if (soft_cata != null && mListType == TYPE_APP_LIST) {
			//soft_cata.setVisibility(View.VISIBLE);
		}
		
		switch(mListType){
		case TYPE_APP_LIST:
			mCurrentURL = reqListBaseURL;//CoachSiteSoftMgrApiAccessor.API_SOFTMGR_LIST;
			break;
		case TYPE_CATEGORY_LIST:
			mCurrentURL = CoachSiteSoftMgrApiAccessor.API_SOFTMGR_TOPIC_APP_LIST;
			//专题列表显示返回导航
			String TopicName = (String)initParaMap.get( "TopicName" );
			String TopicId = (String)initParaMap.get( "TopicId" );
			iTopicId = Integer.valueOf(TopicId);
	        if (ll_top!=null) {
	        	ll_top.setVisibility(View.VISIBLE);
	        	login_top_title = (TextView)findViewById(R.id.login_top_title);
	  		  	login_top_title.setText(TopicName);
	  		  	
	  		  	btn_back=(ImageButton)findViewById(R.id.login_btn_return);
	  		  	btn_back.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						if ( parentView != null )
							parentView.flushView();
					}
				});
	        }
			break;
		case TYPE_SEARCH_LIST:
			
			if ( tv_nodata_main!=null ){
				tv_nodata_main.setText("没有找到相关的搜索结果");
				btn_nodata_reflash.setVisibility(View.GONE);
			}
			
			searchNameType = (Boolean)paraMap.get("searchNameType");
			mCurrentURL = CoachSiteSoftMgrApiAccessor.API_SOFTMGR_LIST;
			keyWord = (String)paraMap.get("keyWord");
			break;
		default:
			break;
		}
		
		//initData();
	}
	
	public void addView(int paramInt) {
		LayoutInflater.from( mContext ).inflate(paramInt, this);
	}
	
	/**
	 * 初始化界面
	 */
	private void initView()
	{
		  lv_required_list=(ListView) findViewById(R.id.lv_required_list);
		  mAdapter=new ListViewAdapter(mContext,lv_required_list);
		  lv_required_list.setAdapter(mAdapter);
		  
		  ll_on_loading_first=(LinearLayout)findViewById(R.id.ll_on_loading);
		  ll_tab_on_loading=(LinearLayout)findViewById(R.id.ll_tab_on_loading);
		  ll_no_data_first=(LinearLayout)findViewById(R.id.ll_no_data);
		  ll_on_loading_bottom=(LinearLayout)findViewById(R.id.ll_on_loading_bottom);
		  tv_nodata_error=(TextView)findViewById(R.id.tv_nodata_error);
		  btn_nodata_reflash=(Button)findViewById(R.id.btn_nodata_reflash);
		  ll_no_data_bottom = (LinearLayout) findViewById(R.id.scroll_no_data);
		  
		  tv_nodata_main = (TextView) findViewById(R.id.tv_nodata_main);
		  
		  ll_top = findViewById(R.id.ll_top);
		  
		  soft_cata = findViewById(R.id.soft_cata);
		  
		  lv_required_list.setOnItemClickListener(new ListItemClickListener());
		  btn_nodata_reflash.setOnClickListener(new ReflashClickListener());
	}
	
	private void setCateLable(ArrayList<SoftCategoryItem> listCatagory){
		
		if (listCatagory==null) return;
		
		TextView tmp_soft_cata;
		
		for (int i = 0; i < listCatagory.size(); i++) {
			
			SoftCategoryItem catagory = listCatagory.get( i );
			
			int categoryResID = getResources().getIdentifier("soft_cata_"+(i+1), "id", getContext().getPackageName());
			tmp_soft_cata = (TextView)findViewById( categoryResID );
			tmp_soft_cata.setText(catagory.name);
			tmp_soft_cata.setTag( catagory );
			tmp_soft_cata.setOnClickListener( catagorySearchListener );
			
			if (i==0) {
				selCataLable = tmp_soft_cata;
				catagoryID = catagory.id;
			}
			//最多显示8个分类
			if (i==7){
				break;
			}
		}
	}
	
	View.OnClickListener catagorySearchListener = new View.OnClickListener(){
		public void onClick(View v) {
			
			if (v instanceof TextView) {
				
				SoftCategoryItem catagory = (SoftCategoryItem)v.getTag();
				
				if (catagoryID == catagory.id) {
					return ;
				}
				
				if ( mIsDownloading ){
					CrashTool.toastShowSpacTime(mContext, "正在加载,请稍后...");
					return;
				}
				
				selCataLable.setTextColor(Color.parseColor("#054F83"));
				selCataLable.setBackgroundDrawable(null); 
				selCataLable = (TextView)v;
				selCataLable.setTextColor(Color.parseColor("#ffffff"));
				selCataLable.setBackgroundResource(R.drawable.soft_mgr_soft_list_cata_sel_gb);
				
				catagoryID = catagory.id;
				
				tabInitData();
			}
		}
	};
	
	/**
	 * 游戏模块请求URL设置
	 */
	public void setReqBaseURLForGame(String reqTypeURL, String reqListURL){
		this.reqTypeBaseURL = reqTypeURL;
		this.reqListBaseURL = reqListURL;
		mCurrentURL = this.reqListBaseURL;
	}
	
	/**
	 * 初始数据
	 */
	public void initData()
	{
		ll_no_data_first.setVisibility(View.GONE);
		ll_tab_on_loading.setVisibility(View.GONE);
		//加载数据
		ll_on_loading_first.setVisibility(View.VISIBLE);
		nextPage=1;
		
		loadSoftInfo(EVENT_FIRST_LOADING);
	}

	/**
	 * Tab分类初始数据
	 */
	private void tabInitData()
	{
		ll_no_data_first.setVisibility(View.GONE);
		nextPage=1;
		//加载数据
		lv_required_list.setVisibility(View.GONE);
		ll_tab_on_loading.setVisibility(View.VISIBLE);
		loadSoftInfo(EVENT_FIRST_LOADING);
	}
	
	/**
	 * 加载数据
	 */
	private void loadSoftInfo(int what)
	{
		mIsDownloading=true;//表示正在下载
		final int finalWhat=what;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				try {
					
					if (soft_cata != null && mListType == TYPE_APP_LIST && catagoryID==0) {
						
						if ( softCategoryResultCache==null || softCategoryResultCache.isbNetworkProblem() ) {
							softCategoryResultCache = CoachSiteSoftMgrApiAccessor.getSoftCategoryList(reqTypeBaseURL,1);
						}
						softCategoryResult = softCategoryResultCache;
						
						if  (softCategoryResult.itemList.size()>0) {
							SoftCategoryItem firstCatagory = softCategoryResult.itemList.get(0);
							catagoryID = firstCatagory.id;
						}
					}
					
					//下载列表数据
					ServerResult<SoftInfo> result = null;
					
					String urlStr=null;
					//分类 catagoryID   专题  搜索
					switch(mListType){
						case TYPE_APP_LIST:
							urlStr = mCurrentURL+catagoryID+"?"+CoachSiteSoftMgrApiAccessor.PAGE_NUMBER+"="+nextPage;
							result = CoachSiteSoftMgrApiAccessor.getSoftAppList(urlStr);
							break;
						case TYPE_CATEGORY_LIST:
							urlStr = mCurrentURL+iTopicId+"?"+CoachSiteSoftMgrApiAccessor.PAGE_NUMBER+"="+nextPage;
							result = CoachSiteSoftMgrApiAccessor.getSoftAppList(urlStr);
							break;
						case TYPE_SEARCH_LIST:
							urlStr =mCurrentURL;
							if ( searchNameType ) {
								//输入文字
								result = CoachSiteSoftMgrApiAccessor.getSoftAppListByKeyWord("name", keyWord, nextPage, 
										CoachSiteSoftMgrApiAccessor.API_SOFTMGR_SEARCH_BY_NAME_LIST);
							}else{
								//直接点击
								result = CoachSiteSoftMgrApiAccessor.getSoftAppListByKeyWord("keyword", keyWord, nextPage, 
										CoachSiteSoftMgrApiAccessor.API_SOFTMGR_SEARCH_LIST);
							}
							break;
						default:
							break;
					}
					
					tempList=result.itemList;
					isLast=result.getPageInfo().isLastPage();
					lastPageInfo = result.getPageInfo();
					if(tempList!=null&&tempList.size()>0)
					{
						//loadIcon(result.itemList);//加载图标
					}
					result=null;
					nextPage++;//分页页码加一页
				} catch (Exception e) {
					if((e instanceof MalformedURLException)||(e instanceof IOException)||(e instanceof SocketTimeoutException)){ //网络异常
						if(nextPage == 1)
							sendMessage(EVENT_CONNECTION_FAILED);
						else
							sendMessage(EVENT_BOTTOM_CONNECTION_FAILED);
					}
					else
						e.printStackTrace();
					tempList=null;
				}
				
				Message msg = mEventHandler.obtainMessage(finalWhat);
				msg.sendToTarget();
			}
		}).start();
	}
	
	/**
	 * 加载图标
	 * @param list
	 */
	private void loadIcon(List<SoftInfo> list)
	{
		final List<SoftInfo> finalList=list;
		new Thread(new Runnable() {
			
			@Override
			public void run() {
				for(int i=0;i<finalList.size();i++)
				{
					final SoftInfo sInfo=finalList.get(i);
					loadSingleIcon(sInfo);
					if(i%5==0||i==finalList.size()-1)
						sendMessage(EVENT_COMMON);
				}//end for
			}
		}).start();
	}
	
	/**
	 * 加载指定软件对象的图标
	 * @param info
	 */
	private void loadSingleIcon(SoftInfo sInfo)
	{
		String iconUrl=sInfo.getIconUrl();
		if(iconUrl!=null)
			iconUrl=iconUrl.replaceAll("\\\\", "/");
		//从url路径中抽取文件名
		String iconFileName=FileUtil.getFileNameFromPath(iconUrl, true);
		sInfo.setIconPath(SystemConst.DOWNLOAD_DIR+iconFileName);
		//缓存目录是否已经存在该图片
		boolean flag=FileUtil.isFileExits(SystemConst.DOWNLOAD_DIR, iconFileName);
		Bitmap icon=null;
		//缓存中存该图片了，取缓存图片
		if(flag)
			icon=BitmapFactory.decodeFile(sInfo.getIconPath());
		else{
			try {
				HttpURLConnection conn=SoftMgrUtil.getConnection(iconUrl);
				icon=BitmapFactory.decodeStream(conn.getInputStream());
				if(conn!=null)
					conn.disconnect();
				//网络上没取到图片，使用默认图片
				if(icon==null)
					icon=defBmp;
				else
					//将图片保存到缓存目录
					FileUtil.saveImageFile(SystemConst.DOWNLOAD_DIR, iconFileName, icon);
			} catch (Exception e) {
				icon=defBmp;
			}
			
		}//end if
		sInfo.setIcon(icon);
	}
	 
	private void sendMessage(int what)
	{
		Message msg=new Message();
		msg.what=what;
		mEventHandler.sendMessage(msg);
	}
	
	/**
	 * 清除缓存
	 */
	@Override
	public void clearCache()
	{
		try {
			mContext.unregisterReceiver(mUninstallReceiver);//注销应用安装与卸载监听
			mContext.unregisterReceiver(mDownloadStatusReceiver);//注销下载监听
			mContext.unregisterReceiver(mLoginReceiver);//注销登录监听
			
			/*
			for(SoftInfo sInfo:mItems)
			{
				Bitmap bmp=sInfo.getIcon();
				if(bmp!=null&&!bmp.isRecycled())
				{
					if(bmp!=defBmp)
						bmp.recycle();
				}
			}
			mItems.clear();
			*/
			//mItems=null;
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}

	
	/*
	@Override
	protected void onDestroy() {
		clearCache();
		super.onDestroy();
	}
	 */
	
	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		if(mAdapter!=null){
			mAdapter.reflashStatus();
		}
	}


	/******************************内部类区*********************************************/
    
    /**
     * 刷新数据的点击事件
     */
    private class ReflashClickListener implements OnClickListener{

		@Override
		public void onClick(View v) {
			
			if (soft_cata != null && mListType == TYPE_APP_LIST) {
				tabInitData();
			} else {
				initData();
			}
		}
    	
    }// end ReflashClickListener
	
    /**
     * 列表的Adapter
     */
    private class ListViewAdapter extends BaseAdapter {
    	
    	private Context mContext;
    	private ListView mSoftListView;
    	private List<SoftInfo> mListViewItems;
    	private LayoutInflater mInflater;
    	private AsyncImageLoader mAsyncImageLoader;	
    	/**服务端softID 过滤重复记录*/
    	private HashMap<String, String> themeIDMap = new HashMap<String, String>();	
    	private boolean mBusy = false; //标识是否存在滚屏操作
    	
    	
		public ListViewAdapter(Context ctx, ListView softListView) {
			
			mContext=ctx;
			mListViewItems=new ArrayList<SoftInfo>();
			mAsyncImageLoader = new AsyncImageLoader();
			mSoftListView = softListView;
			mSoftListView.setOnScrollListener(onScrollListener);
			mInflater=(LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}

		public void clearListItems(){
			mListViewItems.clear();
			themeIDMap.clear();
		}
		
		public void addListItems(List<SoftInfo> _listItems) {
			List<SoftInfo> resultList = filterSoft(_listItems);
			mListViewItems.addAll(resultList);
		}
		
		/**
		 * 过滤掉重复的soft
		 * @param _listSoft
		 */
		private List<SoftInfo> filterSoft(List<SoftInfo> _listSoft){
			
			List<SoftInfo> resultList = new ArrayList<SoftInfo>();
			
			if (_listSoft!=null){
				String softID = "";
				SoftInfo softInfo = null; 
				for (int i = 0; i < _listSoft.size(); i++) {
					softInfo = _listSoft.get(i);
					softID = softInfo.getSid();
					
					if ( themeIDMap.get(softID)==null ){
						themeIDMap.put(softID,softID);
						resultList.add(softInfo);
					}
				}
			}
			
			return resultList;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			
			if ( mListViewItems==null || mListViewItems.size()==0 )
				return null;
			  
			SoftInfo sInfo=mListViewItems.get(position);
			final String infoTitle = sInfo.getTitle();
			View view=convertView;
			Holder holder=null;
			if(view==null)
			{
				holder=new Holder();
				view=mInflater.inflate(R.layout.soft_mgr_soft_list_item, null);
				holder.im_icon=(ImageView)view.findViewById(R.id.im_icon);
				holder.tv_title=(TextView) view.findViewById(R.id.tv_title);
				holder.im_star=(ImageView) view.findViewById(R.id.im_star);
				holder.tv_version=(TextView) view.findViewById(R.id.tv_version);
				holder.tv_size=(TextView) view.findViewById(R.id.tv_size);
				holder.tv_status=(TextView) view.findViewById(R.id.tv_status);
				holder.tv_open_share=(TextView) view.findViewById(R.id.tv_open_share);
				view.setTag(holder);
				
			}else{
				holder=(Holder)view.getTag();
			}
			/*
			Bitmap bmp=sInfo.getIcon();
			if(bmp==null||bmp.isRecycled()||bmp==defBmp)
			{
				if(FileUtil.isFileExits(sInfo.getIconPath()))
				{
					bmp=BitmapFactory.decodeFile(sInfo.getIconPath());
					sInfo.setIcon(bmp);
				}
				if(bmp==null)
					bmp=defBmp;
			}
			*/
			holder.softInfo = sInfo;
			holder.im_icon.setTag(sInfo.getIconUrl());
			//多线程同时加载的情况	  
			Drawable cachedImage = null;
			if (!mBusy) { 
				cachedImage = mAsyncImageLoader.loadDrawable(sInfo.getIconUrl(), new ImageCallback() {
			            public void imageLoaded(Drawable imageDrawable, String imageUrl) {
			            if ( mSoftListView ==null )return; 
			                ImageView imageViewByTag = (ImageView) mSoftListView.findViewWithTag(imageUrl);
			                if (imageViewByTag != null && imageDrawable!=null) {
			                    imageViewByTag.setImageDrawable(imageDrawable);
			                    AlphaAnimation aa = new AlphaAnimation(0.7f, 1.0f);
			                    aa.setDuration(1000);// 设置动画执行的时间
			                    imageViewByTag.startAnimation(aa);
			                }
			            }
			        });
			}else{
				if (mAsyncImageLoader.imageCache.containsKey(sInfo.getIconUrl())) {
					SoftReference<Drawable> softReference = mAsyncImageLoader.imageCache.get(sInfo.getIconUrl());
				    Drawable drawable = softReference.get();
				    if (drawable != null) {
				    	cachedImage = drawable;
				   }
				}
			}
			if (cachedImage == null) {
				holder.im_icon.setImageResource(R.drawable.soft_mgr_defualt_icon);
			}else{
				holder.im_icon.setImageDrawable(cachedImage);
			}

			holder.tv_title.setText(sInfo.getTitle());
			holder.tv_version.setText(mContext.getString(R.string.common_version)+":"+sInfo.getAvailVersion()+" | "+sInfo.getSize());
			holder.tv_size.setText(mContext.getString(R.string.common_size)+":"+sInfo.getSize());
			
			//推荐星级
			int iGrade  = (int)sInfo.getGrade();
			switch (iGrade) {
			case 0:
				holder.im_star.setImageResource(R.drawable.soft_mgr_star_0);
				break;
			case 1:
				holder.im_star.setImageResource(R.drawable.soft_mgr_star_1);
				break;
			case 2:
				holder.im_star.setImageResource(R.drawable.soft_mgr_star_2);
				break;
			case 3:
				holder.im_star.setImageResource(R.drawable.soft_mgr_star_3);
				break;
			case 4:
				holder.im_star.setImageResource(R.drawable.soft_mgr_star_4);
				break;
			case 5:
				holder.im_star.setImageResource(R.drawable.soft_mgr_star_5);
				break;
			default:
				break;
			}
			
			holder.tv_status.setBackgroundResource(R.drawable.soft_mgr_normal_btn_selector);
			holder.tv_status.setTextColor(BLACK);
			//显示状态
			switch (sInfo.getStatus()) {
			//普通状态，不显示
			case DownloadItem.STATUS_NONE:
				holder.tv_status.setText(R.string.common_button_download);
				break;
			//可升级状态，则显示可升级
			case DownloadItem.STATUS_UPGRADABLE:
				holder.tv_status.setText(R.string.common_upgrade);
				holder.tv_status.setTextColor(BLUE);
				break;
			//正在下载,显示暂停
			case DownloadItem.STATUS_DOWNLOADING:
				holder.tv_status.setText(R.string.common_button_pause);
				break;
			//已暂停,显示继续
			case DownloadItem.STATUS_DOWNLOAD_PAUSE:
				holder.tv_status.setText(R.string.common_button_continue);
				break;
			//已下载,显示安装
			case DownloadItem.STATUS_DOWNLOADED:
				holder.tv_status.setText(R.string.common_button_install);
				holder.tv_status.setTextColor(BLUE);
				break;
			//已安装,显示卸载
			case DownloadItem.STATUS_INSTALLED:
				holder.tv_status.setBackgroundResource(R.drawable.soft_mgr_normal_btn_pressed);
				holder.tv_status.setTextColor(WHITE);
				holder.tv_status.setText(R.string.common_has_install);
//				holder.tv_status.setText(R.string.common_button_uninstall);
				break;
			//下载失败,显示重试
			case DownloadItem.STATUS_DOWNLOAD_FAILED:
				holder.tv_status.setText(R.string.common_button_retry);
				break;
			}
			
			final String sSoftID = sInfo.getSid();
			final String sSoftTitle = sInfo.getTitle();
			final String sSoftURL = sInfo.getDownloadUrl();
			final String sSoftFlag = sInfo.getFlag();
			
			holder.tv_status.setOnClickListener(new ButtonClickListener(sInfo));
			holder.tv_open_share.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {		
					
					if ( mListType==TYPE_SEARCH_LIST ) {
						OpenShareTool.showOperDialog(mContext, sSoftTitle ,sSoftURL, sSoftID, shareType, "search", sSoftFlag);
					}else{
						OpenShareTool.showOperDialog(mContext, sSoftTitle ,sSoftURL, sSoftID, shareType, "", sSoftFlag);
					}
				}
			});
			holder.tv_open_share.setText(OpenShareTool.getShareDesc(mContext));
			
			//搜索结果不响应点击事件去，去掉点击背景色
			 if ( mListType==TYPE_SEARCH_LIST ) {
				 //消除点击事件，使得布局内的空间不收到消息
				 view.setClickable(true);
				 view.setLongClickable(true);
			 }
			 
			return view;
		}
    	
		@Override
		public int getCount() {
			
			return mListViewItems.size();
		}

		@Override
		public Object getItem(int position) {
			
			return mListViewItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			
			return position;
		}
		
		//滚动监听,是否滚到底部
		AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {
			
			@Override
			public void onScrollStateChanged(AbsListView view, int scrollState) {
			
		        switch (scrollState) { 
		        case OnScrollListener.SCROLL_STATE_IDLE: //Idle态，进行实际数据的加载显示 
		            mBusy = false; 
		            notifyDataSetChanged();
		            int curSize=mListViewItems.size();
					if(view.getLastVisiblePosition()==curSize-1&&!isLast&&!mIsDownloading){	
						ll_on_loading_bottom.setVisibility(View.VISIBLE);
						ll_no_data_bottom.setVisibility(View.GONE);
						loadSoftInfo(EVENT_LIST_SCROLL_END);
					}
		            break;   
		        case OnScrollListener.SCROLL_STATE_TOUCH_SCROLL: 
		            mBusy = true; 
		            break; 
		        case OnScrollListener.SCROLL_STATE_FLING: 
		            mBusy = true; 
		            break; 
		        default: 
		            break; 
		        } 
		    } 
			
			@Override
			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				
			}
		};
		
		/*
		AbsListView.OnTouchListener onTouchListener = new AbsListView.OnTouchListener(){

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if(event.getAction() == MotionEvent.ACTION_MOVE&&_scrollState!=OnScrollListener.SCROLL_STATE_FLING){  
                    //这里加入加载图片的方法 和setOnScrollListener监听中的方法一样即可  
					
                } 
				return false;
			}
			
		};
		*/
		
		/**
		 * 卸载更新
		 */
		public void uninstallChange(String pkgData){
			for(DownloadItem item:mListViewItems)
			{
				if(("package:"+item.getPkgName()).equalsIgnoreCase(pkgData))
				{
					int status=DownloadService.getDownloadStatus(mContext, item);
	    			item.setStatus(status);
	    			sendMessage(EVENT_COMMON);
	    			break;
				}
			}
		}
		
		public void reflashStatus() {
			for(DownloadItem item:mListViewItems)
			{
				int status=DownloadService.getDownloadStatus(mContext, item);
				item.setStatus(status);
			}
			sendMessage(EVENT_COMMON);
		}
		
		public void changeStatus(DownloadItem item)
		{
			if (item==null)
				return;
			for(DownloadItem localItem:mListViewItems)
			{
				if(item.getSid().equalsIgnoreCase(localItem.getSid()))
				{
					localItem.setStatus(item.getStatus());
					sendMessage(EVENT_COMMON);
					break;
				}
			}
		}
    }//end ListAdater
    
	private class Holder{
		public ImageView im_icon;
		public TextView tv_title;
		public ImageView im_star;
		public TextView tv_version;
		public TextView tv_size;
		public TextView tv_status;
		public TextView tv_open_share;
		public SoftInfo softInfo;
	}
    
    /**
	 * 开始下载
	 */
	private void beginDownload(SoftInfo mItem)
	{
		final SoftInfo finItem = mItem;
		if(mItem!=null)
		{ 
			new Thread(new Runnable() {

				@Override
				public void run() {
					Intent intent=new Intent(mContext,DownloadService.class);
					intent.putExtra(DownloadItem.EXTRA_ME, finItem);
					mContext.startService(intent);
					
				}
				
			}).start();
			
			talk(mItem.getTitle()+":"+mContext.getString(R.string.common_begin_download));
		}
	}


	private void talk(String msg)
	{
		Toast.makeText(mContext, msg, Toast.LENGTH_SHORT).show();
	}
	
    /**
	 * 按钮点击事件
	 */
	private class ButtonClickListener implements OnClickListener{
		private SoftInfo mItem;
		public ButtonClickListener(SoftInfo item){
			mItem = item;
		}
		@Override
		public void onClick(View v) {
			switch (mItem.getStatus()) {
			//普通状态，则下载
			case DownloadItem.STATUS_NONE:
				beginDownload(mItem);
				break;
			//可升级状态，则下载
			case DownloadItem.STATUS_UPGRADABLE:
				beginDownload(mItem);
				break;
			//正在下载状态，则暂停下载
			case DownloadItem.STATUS_DOWNLOADING:
				talk(mItem.getTitle()+":"+mContext.getString(R.string.common_pause_download));
				DownloadService.pauseItem(mItem,mContext);
				break;
			//暂停状态，则继续下载
			case DownloadItem.STATUS_DOWNLOAD_PAUSE:
				DownloadService.continueItem(mItem,mContext);
				talk(mItem.getTitle()+":"+mContext.getString(R.string.common_begin_download));
				break;
			//已下载状态，则安装
			case DownloadItem.STATUS_DOWNLOADED:
				U.installApplication(mContext, mItem);
				break;
			//已安装状态，则卸载
			case DownloadItem.STATUS_INSTALLED:
//				U.uninstallApp(mContext, mItem.getPkgName());
				break;
			//下载失败状态，则下载
			case DownloadItem.STATUS_DOWNLOAD_FAILED:
				beginDownload(mItem);
				break;
			}//end switch
		}
	}
    /**
     * 列表项点击，进入软件详情界面
     */
    private class ListItemClickListener implements OnItemClickListener{

		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			 //搜索结果不响应点击事件去，不打开应用详情
			if ( mListType==TYPE_SEARCH_LIST ) {
				return ;
			}
			
			Holder holder = (Holder) view.getTag();
			if (holder==null)
				return;
			SoftInfo item=holder.softInfo;
			Intent intent=new Intent(mContext,SoftMgrDetailActivity.class);
			int iSoftID = Integer.valueOf(item.getSid());
			intent.putExtra("softID",iSoftID);
			intent.putExtra(DownloadTool.SOFT_FLAG,item.getFlag());
			mContext.startActivity(intent);
		}
    	
    }//end ListItemClickListener
    
    /**
     * 安装与卸载监听
     *
     */
    private class UninstallReceiver extends BroadcastReceiver {
    	@Override
    	public void onReceive(Context context, Intent intent) {
    		
    		String pkgData=intent.getDataString();
    		if(pkgData!=null){
    			if(mAdapter!=null){
    				mAdapter.uninstallChange(pkgData);
    			}
    		}
    	}
	}
    
    /**
     * 登录成功监听器
     */
    private class LoginReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			
			if(mAdapter!=null)
				mAdapter.notifyDataSetChanged();
		}
    }
    
    /**
     * 下载状态改变监听器
     */
    private class DownloadStatusReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			DownloadItem dItem=(DownloadItem) intent.getSerializableExtra(DownloadItem.EXTRA_ME);
			if(dItem!=null){
				if(mAdapter!=null)
					mAdapter.changeStatus(dItem);
			}
		}
    }//end DownloadStatusReceiver

    public static void initCacheData(){
    	/*
    	if (softCategoryResultCache==null){ 
    		new Thread(new Runnable() {
    			
    			@Override
    			public void run() {
    				softCategoryResultCache = CoachSiteSoftMgrApiAccessor.getSoftCategoryList(1);
    			}
    			
    		}).start();
    	}
    	*/
    }
}


















